import datetime

import joblib
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split, learning_curve
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report, roc_auc_score
from xgboost import XGBRegressor, XGBClassifier

from utils.common import data_preprocessing

from utils.log import Logger
class Model:
        def __init__(self, path):
            logfile_name = 'train' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            self.logfile = Logger('../', logfile_name).get_logger()
            self.logfile.info('开始创建')
            self.path = '../data/train.csv'


def model_train(data,features,logger):



# 加载数据集
# 请确保 'train.csv' 文件和您的Python脚本在同一个目录下

    # 将特征和标签分开
    X = df.drop('Attrition', axis=1)
    y = df['Attrition']

    # 识别分类和数值特征
    categorical_features = X.select_dtypes(include=['object']).columns
    numerical_features = X.select_dtypes(include=['int64', 'float64']).columns

    # 'EmployeeNumber' 只是一个标识符，通常对模型没有帮助，所以我们删除它
    X = X.drop('EmployeeNumber', axis=1)
    numerical_features = numerical_features.drop('EmployeeNumber')


    # 为数值和分类特征创建预处理管道
    # 数值特征进行标准化，分类特征进行独热编码
    numerical_transformer = StandardScaler()
    categorical_transformer = OneHotEncoder(handle_unknown='ignore')

    # 使用ColumnTransformer将转换器应用于相应的列
    preprocessor = ColumnTransformer(
        transformers=[
            ('num', numerical_transformer, numerical_features),
            ('cat', categorical_transformer, categorical_features)
        ])

    # --- 1. 逻辑回归模型 ---
    # 创建包含预处理和分类器的完整管道
    lr_model = Pipeline(steps=[('preprocessor', preprocessor),
                          ('classifier', LogisticRegression(solver='liblinear'))])

    # 将数据分为训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # 训练逻辑回归模型
    lr_model.fit(X_train, y_train)

    # 在测试集上进行预测
    y_pred_lr = lr_model.predict(X_test)
    y_proba = lr_model.predict_proba(X_test)[:, 1]

    # 评估模型
    accuracy_lr = accuracy_score(y_test, y_pred_lr)
    report_lr = classification_report(y_test, y_pred_lr)

    print("--- 逻辑回归模型 ---")
    print(f"模型准确率: {accuracy_lr}")
    print("分类报告:")
    print(report_lr)
    print(f"ROC AUC: {roc_auc_score(y_test, y_proba)}")

    joblib.dump(lr_model, "lr_0912.pkl")

if __name__ == '__main__':
    df = pd.read_csv('../data/train.csv')
    pm = Model('../data/train.csv')
    # print(pm.data_source)
    # ana_data(pm.data_source)
    feature_columns =  ['Age', 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', 'EducationField', 'EnvironmentSatisfaction', 'Gender', 'JobInvolvement', 'JobLevel', 'JobRole', 'JobSatisfaction', 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', 'Over18', 'OverTime', 'PercentSalaryHike', 'PerformanceRating', 'RelationshipSatisfaction', 'StandardHours', 'StockOptionLevel', 'TotalWorkingYears', 'TrainingTimesLastYear', 'WorkLifeBalance', 'YearsAtCompany', 'YearsInCurrentRole', 'YearsSinceLastPromotion', 'YearsWithCurrManager']
    model_train(df, feature_columns, pm.logfile)

# 验证过拟合情况
# 方法一：比较训练集和测试集的准确率
#     train_score = lr_model.score(X_train, y_train)
#     test_score = lr_model.score(X_test, y_test)
#
#     print(f'训练集准确率：{train_score:.4f}')
#     print(f'测试集准确率：{test_score:.4f}')
#     print(f'准确率差值：{train_score - test_score:.4f}')